package model

import (
	"gorm.io/gorm"
)

// MedicalRecord 病历模型
type MedicalRecord struct {
	gorm.Model
	RecordNo        string `gorm:"type:varchar(32);not null;unique;comment:病历号"`
	ConsultationID  int64  `gorm:"type:bigint;not null;comment:问诊ID"`
	DoctorID        int64  `gorm:"type:bigint;not null;index;comment:医生ID"`
	PatientID       int64  `gorm:"type:bigint;not null;index;comment:患者ID"`
	Diagnosis       string `gorm:"type:varchar(200);comment:诊断"`
	ChiefComplaint  string `gorm:"type:text;comment:主诉"`
	PresentIllness  string `gorm:"type:text;comment:现病史"`
	PastHistory     string `gorm:"type:text;comment:既往史"`
	PhysicalExam    string `gorm:"type:text;comment:体格检查"`
	Treatment       string `gorm:"type:text;comment:治疗方案"`
	TemplateID      string `gorm:"type:varchar(50);comment:病历模板ID"`
	Rating          int    `gorm:"type:tinyint(1);comment:评分:1-5星"`
	RatingComment   string `gorm:"type:text;comment:评价内容"`
}

// CreateMedicalRecord 创建病历
func (r *MedicalRecord) CreateMedicalRecord(db *gorm.DB) error {
	return db.Create(&r).Error
}

// GetMedicalRecordByID 根据ID查询病历
func (r *MedicalRecord) GetMedicalRecordByID(db *gorm.DB, id int64) error {
	return db.Where("id = ?", id).First(&r).Error
}

// UpdateMedicalRecord 更新病历
func (r *MedicalRecord) UpdateMedicalRecord(db *gorm.DB) error {
	return db.Save(&r).Error
}

// GetMedicalRecordList 获取病历列表
func GetMedicalRecordList(db *gorm.DB, patientId, doctorId int64, startDate, endDate string, page, pageSize int) ([]MedicalRecord, int64, error) {
	var records []MedicalRecord
	var total int64

	query := db.Model(&MedicalRecord{})

	if patientId > 0 {
		query = query.Where("patient_id = ?", patientId)
	}
	if doctorId > 0 {
		query = query.Where("doctor_id = ?", doctorId)
	}
	if startDate != "" {
		query = query.Where("created_at >= ?", startDate)
	}
	if endDate != "" {
		query = query.Where("created_at <= ?", endDate)
	}

	// 统计总数
	if err := query.Count(&total).Error; err != nil {
		return nil, 0, err
	}

	// 使用分页作用域
	if err := query.Scopes(Paginate(page, pageSize)).Order("created_at DESC").Find(&records).Error; err != nil {
		return nil, 0, err
	}

	return records, total, nil
}

